from predictor import load_label_list
from recact.models import Contentlist

PICTURE_ROOT_PATH = "/static/images/"


def get_related_content(pred_result):
    """
    根据预测标签获得相关内容
    由于使用了数据库，因此所有查询内容可以统一完成
    """
    class_obj_list = Contentlist.objects.filter(label_name_en = pred_result+"\n").all()
    if not class_obj_list:
        raise ValueError(f"no such class named {pred_result}")
    
    baike_content = get_baike_content(class_obj_list)
    related_link_list, related_link_title, related_link_abstract = get_relate_link(class_obj_list)
    image_path = get_img_path(pred_result[2:])
    return baike_content, related_link_list, image_path, related_link_abstract, related_link_title

    

def get_baike_content(class_obj_list):
    """
    根据标签获取对应的百科内容
    """
    baike_content = ""
    for i in class_obj_list:
        if i.is_baike:
            baike_content = i.baike_field
    return baike_content

def get_relate_link(class_obj_list):
    """
    根据标签获取对应的百度相关链接
    """
    class_obj_list_1 = [i for i in class_obj_list if i.is_baike == 0]
    related_link_list = [i.link for i in class_obj_list_1 if i.link and i.link_abstract != "0"]
    related_link_title = [i.link_title for i in class_obj_list if i.link and i.link_abstract != "0"]
    related_link_abstract = [i.link_abstract[:100] for i in class_obj_list if i.link and i.link_abstract != "0"]
    return related_link_list, related_link_title, related_link_abstract


def get_img_path(pred_result):
    """
    根据标签获取数据库内的图片路径
    """
    img_root_path = '/static/images/'
    pred_result = pred_result.replace(" ", "")
    img_path = img_root_path + pred_result + '.jpg'
    return img_path
